<template>
  <div>
    <button @click="changeMsg">change</button>
    <div>{{ message }}</div>
    <p>------------</p>
    <button @click="change">修改 customRef</button>
    <div>{{ name }}</div>
  </div>
</template>

<script setup lang="ts">
// shallowRef 创建一个跟踪自身 .value 变化的 ref，但不会使其值也变成响应式的(值可更新 但是视图不更新)
// triggerRef 强制更新页面DOM
// customRef 是个工厂函数要求我们返回一个对象 并且实现 get 和 set  适合去做防抖之类的
import { Ref, shallowRef, triggerRef, customRef } from "vue";
type Obj = {
  name: string;
};
let message: Ref<Obj> = shallowRef({
  name: "小满",
});

const changeMsg = () => {
  message.value.name = "大满";
  //  triggerRef(message)
};

function myRef<T = any>(value: T) {
  let timer: any;
  return customRef((track, trigger) => {
    return {
      get() {
        track();
        return value;
      },
      set(newVal) {
        clearTimeout(timer);
        timer = setTimeout(() => {
          console.log("触发了set");
          value = newVal;
          trigger();
        }, 500);
      },
    };
  });
}

const change = () => {
  name.value = "大满";
};
const name = myRef<string>("小满");
</script>

<style></style>
